package com.aloda.config;

import com.aloda.interceptor.LoginInterceptor;
import com.aloda.interceptor.RefreshTokenInterceptor;
import com.aloda.properties.TokenProperties;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.config.annotation.*;

@Slf4j
@Configuration
public class WebConfiguration implements WebMvcConfigurer {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private TokenProperties tokenProperties;
//
//    /**
//     * 跨域请求配置
//     * @param registry
//     */
//    @Override
//    public void addCorsMappings(CorsRegistry registry) {
//        log.info("开启跨域请求配置...");
//        registry.addMapping("/**")
//                .allowedOriginPatterns("*")
//                .allowedMethods("GET", "POST", "PUT", "DELETE","OPTIONS")
//                .allowedHeaders("*")
//                .allowCredentials(true);
//    }
    @Bean
    public FilterRegistrationBean<CorsFilter> corsFilter() {
        log.info("开启跨域请求配置...");
        FilterRegistrationBean<CorsFilter> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setFilter(new CorsFilter());
        registrationBean.addUrlPatterns("/*"); // 应用到所有URL
        return registrationBean;
    }

    /**
     * 开启拦截器配置
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry){
        log.info("开启拦截器配置...");
        // order升序执行
        // 拦截需要刷新token过期时间的路径
        registry.addInterceptor(new RefreshTokenInterceptor(tokenProperties,stringRedisTemplate))
                .addPathPatterns("/user/**").order(0);
        // 拦截需要登录的路径
        registry.addInterceptor(new LoginInterceptor())
                .addPathPatterns("/user/**")
                .excludePathPatterns("/user/tag/**")
                .excludePathPatterns("/user/user/register")
                .excludePathPatterns("/user/user/login")
                .excludePathPatterns("/common/**")
                .order(1);
    }
//    /**
//     * 设置静态资源映射 以免无法访问knife4j接口文档
//     * @param registry
//     */
//    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
//        log.info("开始设置静态资源映射...");
//        registry.addResourceHandler("/doc.html").addResourceLocations("classpath:/META-INF/resources/");
//        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
//    }
}
